package com.tangguangdi.base.db.config;

import com.tangguangdi.base.db.generator.controller.GeneratorController;
import com.tangguangdi.base.db.generator.service.DbService;
import com.tangguangdi.base.db.generator.service.GeneratorService;
import com.tangguangdi.base.db.properties.DbProperties;
import com.tangguangdi.base.db.properties.GeneratorProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@PropertySource("classpath:/bootstrap.properties")
public class DbAutoConfiguration {

    @Value("#{'${spring.datasource.url:}'}")
    private String url;

    @Value("#{'${spring.datasource.username:root}'}")
    private String username;

    @Value("#{'${spring.datasource.password:root}'}")
    private String password;

    @Value("#{'${spring.datasource.driver-class-name:com.mysql.cj.jdbc.Driver}'}")
    private String driverClassName;

    /**
     * max-db
     */
    @Bean
    @ConfigurationProperties(prefix = "max.db")
    public DbProperties dbProperties() {
        return new DbProperties();
    }

    @Bean
    public DbService dbService(DbProperties dbProperties) {
        GeneratorProperties properties = dbProperties.getGenerator();
        List<String> urls = Arrays.stream(url.split(":|\\/|\\?"))
                .filter(str -> !"".equals(str))
                .collect(Collectors.toList());
        if (urls.size() > 5) {
            properties.setType(urls.get(1).toUpperCase());
            properties.setUrl(urls.get(2).concat(":").concat(urls.get(3)));
            properties.setSchema(urls.get(4));
            properties.setPostfix(urls.get(5));
        }
        properties.setUsername(username);
        properties.setPassword(password);
        properties.setDriverClassName(driverClassName);
        return new DbService(dbProperties);
    }

    @Bean
    public GeneratorService generatorService() {
        return new GeneratorService();
    }

    @Bean
    public GeneratorController codeController() {
        return new GeneratorController();
    }
}
